import React, { Component } from "react";

import FilterTitle from "../FilterTitle";
import FilterPicker from "../FilterPicker";
import FilterMore from "../FilterMore";

import styles from "./index.module.css";

// 导入自定义的API方法
import { API } from "../../../../utils/api";
// 导入react-spring库
import { Spring } from "react-spring/renderprops";
import {getCity} from '../../../../utils/city'
// 标题高亮状态
// true 表示高亮； false 表示不高亮
const titleSelectedStatus = {
  area: false,
  mode: false,
  price: false,
  more: false
};
// setCity('{"label": "北京","value": "AREA|88cff55c-aaa4-e2e0"}')
// 获取到本地存储中的当前城市value
// const { value } = JSON.parse(localStorage.getItem("city"));
const {value} = getCity()

// 提供选中状态
const selectedValue = {
  area: ["area", "null"],
  mode: ["null"],
  price: ["null"],
  more: []
};
export default class Filter extends Component {
  state = {
    titleSelectedStatus,
    // 控制FilterPicker或者FilterMore组件的展示或者隐藏
    openType: "",
    // 获取所有的房屋查询数据
    FiltersDate: {},
    selectedValue
  };
  componentDidMount() {
    this.getFiltersDate();
    // 获取到body
    this.htmlBody = document.body;
  }
  // 点击标题菜单实现高亮
  // 注意：this指向的问题！！！
  // 说明：要实现完整的功能，需要后续的组件配合完成！
  onTitleClick = type => {
    // 为body添加样式
    this.htmlBody.className = "body-fixed";
    const { titleSelectedStatus, selectedValue } = this.state;
    // 创建新的标题选中状态数据
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    // 使用Object.keys方法遍历标题的选中状态
    Object.keys(titleSelectedStatus).forEach(item => {
      const selectedVal = selectedValue[item];

      if (item === type) {
        newTitleSelectedStatus[item] = true;
        return;
      }
      if (
        item === "area" &&
        (selectedVal.length !== 2 || selectedVal[0] !== "area")
      ) {
        newTitleSelectedStatus[item] = true;
      } else if (item === "mode" && selectedVal[0] !== "null") {
        newTitleSelectedStatus[item] = true;
      } else if (item === "price" && selectedVal[0] !== "null") {
        newTitleSelectedStatus[item] = true;
      } else if (item === "more" && selectedVal.length !== 0) {
        newTitleSelectedStatus[item] = true;
      } else {
        newTitleSelectedStatus[item] = false;
      }
    });
    this.setState(() => {
      return {
        titleSelectedStatus: newTitleSelectedStatus,
        openType: type
      };
    });
  };
  // 取消-隐藏对话框
  onCancel = type => {
    this.htmlBody.className = "";
    const { titleSelectedStatus, selectedValue } = this.state;
    // 创建新的标题选中状态数据
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    const selectedVal = selectedValue[type];
    if (
      type === "area" &&
      (selectedVal.length !== 2 || selectedVal[0] !== "area")
    ) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }
    this.setState(() => {
      return {
        openType: "",
        titleSelectedStatus: newTitleSelectedStatus
      };
    });
  };
  // 确定-隐藏对话框
  onSave = (type, value) => {
    // 取消htmlBody样式
    this.htmlBody.className = "";
    // console.log(type, value);
    const { titleSelectedStatus } = this.state;
    // 创建新的标题选中状态数据
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    const selectedVal = value;
    if (
      type === "area" &&
      (selectedVal.length !== 2 || selectedVal[0] !== "area")
    ) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }

    const newSelectedValue = {
      ...this.state.selectedValue,
      [type]: value
    };
    // 筛选条件数据
    const filters = {};
    const { area, mode, price, more } = newSelectedValue;
    // 区域
    const areaKey = area[0];
    let areaValue = "null";
    if (area.length === 3) {
      areaValue = area[2] !== "null" ? area[2] : area[1];
    }
    filters[areaKey] = areaValue;
    // 方式和租金
    filters.mode = mode[0];
    filters["price"] = price[0];
    // 更多筛选条件
    filters.more = more.join(",");
    // console.log(filters);
    // 将筛选数据传递到父组件中
    this.props.onFilter(filters);

    this.setState(() => {
      return {
        openType: "",
        titleSelectedStatus: newTitleSelectedStatus,
        selectedValue: newSelectedValue
      };
    });
  };
  // 发送请求获取所有的房屋查询条件
  getFiltersDate = async () => {
    const { data: res } = await API.get(`/houses/condition?id=${value}`);
    this.setState(() => {
      return {
        FiltersDate: res.body
      };
    });
  };
  // 渲染FilterPicker组件的方法
  renderFilterPicker = () => {
    const {
      openType,
      FiltersDate: { area, subway, rentType, price },
      selectedValue
    } = this.state;
    if (openType !== "area" && openType !== "mode" && openType !== "price") {
      return null;
    }
    // 根据openType 来获取当前筛选条件数据
    let data = [];
    let cols = 3;
    let defaultValue = selectedValue[openType];
    switch (openType) {
      case "area":
        // 获取区域数据
        data = [area, subway];
        cols = 3;
        break;
      case "mode":
        //  获取合租数据
        data = rentType;
        cols = 1;
        break;
      case "price":
        //  获取价格
        data = price;
        cols = 1;
        break;
      default:
        break;
    }
    return (
      <FilterPicker
        key={openType}
        onCancel={this.onCancel}
        onSave={this.onSave}
        data={data}
        cols={cols}
        type={openType}
        defaultValue={defaultValue}
      />
    );
  };
  // 渲染renderFilterMore 组件方法
  renderFilterMore = () => {
    const {
      openType,
      FiltersDate: { characteristic, floor, oriented, roomType },
      selectedValue
    } = this.state;
    const data = { characteristic, floor, oriented, roomType };
    if (openType !== "more") {
      return null;
    }
    const defaultValues = selectedValue.more;
    return (
      <FilterMore
        data={data}
        onCancel={this.onCancel}
        onSave={this.onSave}
        type={openType}
        defaultValues={defaultValues}
      />
    );
  };
  renderMask() {
    const { openType } = this.state;
    const isHide = openType === "more" || openType === "";
    return (
      <Spring from={{ opacity: 0 }} to={{ opacity: isHide ? 0 : 1}}>
        {props => {
          if (props.opacity === 0) {
            return null;
          }
          return (
            <div
              style={props}
              className={styles.mask}
              onClick={() => this.onCancel(openType)}
            />
          );
        }}
      </Spring>
    );
  }
  render() {
    const { titleSelectedStatus } = this.state;

    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}
        {this.renderMask()}

        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle
            titleSelectedStatus={titleSelectedStatus}
            onClick={this.onTitleClick}
          />

          {/* 前三个菜单对应的内容： */}
          {this.renderFilterPicker()}
          {/* 最后一个菜单 */}
          {this.renderFilterMore()}
        </div>
      </div>
    );
  }
}
